package com.example.unisys.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.unisys.common.Response;
import com.example.unisys.common.STATUS;
import com.example.unisys.entity.StuCourse;
import com.example.unisys.entity.Student;
import com.example.unisys.form.BigStudentForm;
import com.example.unisys.dao.ExamMapper;
import com.example.unisys.dao.HistStuCourseMapper;
import com.example.unisys.dao.StuExamMapper;
import com.example.unisys.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping(value = "/apis/v1/students", produces = "application/json; charset=utf-8")
public class StudentController {

    @Autowired
    StudentService studentService;

    @Autowired
    CourseService courseService;

    @Autowired
    UserService userService;

    @Autowired
    StuCourseService stuCourseService;

    @Autowired
    CourseSaleService courseSaleService;

    @Autowired
    TagService tagService;

    @Autowired
    StuExamMapper stuexamMapper;

    @Autowired
    ExamMapper examMapper;

    @Autowired
    HistStuCourseMapper histStuCourseMapper;

/*
    @RequestMapping(value = "", method = {RequestMethod.GET})
    public HashMap<String, Object> getStudents(@CookieValue("Admin-Token") String token, @RequestParam("limit") int limit, @RequestParam("page") int page, @RequestParam("searchText") String searchText) {
        int newlimit = (page - 1) * limit;
        int pagesize = limit;
        HashMap<String, Object> res = new HashMap();
        HashSet<Student> hs = new HashSet();
        String username = JWTUtil.getUsername(token);
        User user = userService.getInfo(username);
        if (user.getUser_type() == 2) {
            if (searchText.equals("")) {
                List<Student> stus = studentService.getMainStu(user.getMain_school(), newlimit, pagesize);
                int total = studentService.getMainStuNum(user.getMain_school());
                res.put("code", 20000);
                res.put("data", stus);
                res.put("total", total);
                return res;
            } else {
                List<Student> stus = new ArrayList<>();
                List<Student> tmp1 = studentService.getByNameMain(searchText, user.getMain_school());
                for (Student s : tmp1)
                    hs.add(s);
                List<Student> tmp2 = studentService.getByPhoneMain(searchText, user.getMain_school());
                for (Student s : tmp2)
                    hs.add(s);
                try {
                    Student s = studentService.getById(Long.parseLong(searchText));
                    hs.add(s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                for (Student s : hs)
                    stus.add(s);
                res.put("code", 20000);
                res.put("data", stus);
                res.put("total", stus.size());
                return res;
            }
        } else if (user.getUser_type() == 3) {
            if (searchText.equals("")) {
                List<Student> stus = studentService.getSubStu(user.getMain_school(), user.getSub_school(), newlimit, pagesize);
                int total = studentService.getStuNum(user.getMain_school(), user.getSub_school());
                res.put("code", 20000);
                res.put("data", stus);
                res.put("total", total);
                return res;
            } else {
                List<Student> stus = new ArrayList<>();
                List<Student> tmp1 = studentService.getByPhone(searchText, user.getMain_school(), user.getSub_school());
                for (Student s : tmp1)
                    hs.add(s);
                List<Student> tmp2 = studentService.getByName(searchText, user.getMain_school(), user.getSub_school());
                for (Student s : tmp2)
                    hs.add(s);
                try {
                    Student s = studentService.getById(Long.parseLong(searchText));
                    hs.add(s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                for (Student s : hs)
                    stus.add(s);
                res.put("code", 20000);
                res.put("data", stus);
                res.put("total", stus.size());
                return res;
            }
        }
        else {
            res.put("code",400);
            res.put("message","something happen");
            return res;
        }
    }

    */

    /*
     * 获取系统学生列表
     * */
    @RequestMapping(value = "/System", method = {RequestMethod.GET})
    public Response getSystemStudent(@CookieValue("Admin-Token") String token, @RequestParam("limit") int limit, @RequestParam("page") int page) {
        int newlimit = (page - 1) * limit;
        int pagesize = limit;
        List<Student> students = studentService.getSysStu(newlimit, pagesize);
        List<BigStudentForm> bigStudentForms = new ArrayList<>();
        students.forEach(stu -> {
            BigStudentForm bigStudentForm = BigStudentForm.builder().build();
            bigStudentForm.setStu(stu);
            bigStudentForm.setCourses(stuCourseService.getById(stu.getExam_id()));
            bigStudentForm.courses.forEach(course -> {
                course.setCatalogtree("");
            });
            bigStudentForms.add(bigStudentForm);

        });
//        for (int i = 0; i < stus.size(); i++) {
//            BigStudentForm big = BigStudentForm.builder().build();
//            big.setStu(stus.get(i));
//            big.setCourses(stuCourseService.getById(stus.get(i).getExam_id()));
//            bigs.add(big);
//            for (StuCourse sc : big.courses)
//                sc.setCatalogtree("");
//        }
        return Response.builder().status(STATUS.SUCCESS).data(bigStudentForms).total(studentService.getAllStuNum()).build();
    }

    /*
     * 根据学校获取学生列表
     * */
    @RequestMapping(value = "/getBySchool", method = {RequestMethod.GET})
    public Response SearchBySchool(@RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school, @RequestParam("limit") int limit, @RequestParam("page") int page) {
        int newlimit = (page - 1) * limit;
        int pagesize = limit;
        List<BigStudentForm> bigStudentForms = new ArrayList<>();
        List<Student> students = new ArrayList<>();
        int total = 0;
        if (main_school.equals(sub_school)) {
            students = studentService.getMainStu(main_school, newlimit, pagesize);
            total = studentService.getMainStuNum(main_school);
        } else {
            students = studentService.getSubStu(main_school, sub_school, newlimit, pagesize);
            total = studentService.getStuNum(main_school, sub_school);
        }
        students.forEach(stu -> {
            BigStudentForm bigStudentForm = BigStudentForm.builder().build();
            bigStudentForm.setStu(stu);
            bigStudentForm.setCourses(stuCourseService.getById(stu.getExam_id()));
            bigStudentForm.courses.forEach(course -> {
                course.setCatalogtree("");
            });
            bigStudentForms.add(bigStudentForm);

        });
        return Response.builder().status(STATUS.SUCCESS).data(bigStudentForms).total(total).build();

    }

    /*
     * 搜索
     * */
/*    @RequestMapping(value = "/Search", method = {RequestMethod.GET})
    public Response Search(@RequestParam("searchText") String searchText, @RequestParam("user_type") Integer user_type,
                           @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school) {
        HashMap<String, Object> queryMap = new HashMap<>();
        List<Student> students = studentService.getStudentsBySearch(queryMap);
        List<BigStudentForm> bigStudentForms = new ArrayList<>();

        System.out.println("search stus size is " + students.size());
        students.forEach(stu -> {
            BigStudentForm bigStudentForm = BigStudentForm.builder().build();
            bigStudentForm.setStu(stu);
            bigStudentForm.setCourses(stuCourseService.getById(stu.getExam_id()));
            bigStudentForm.courses.forEach(course -> {
                course.setCatalogtree("");
            });
            bigStudentForms.add(bigStudentForm);
        });
        return Response.builder().status(STATUS.SUCCESS).data(bigStudentForms).total(bigStudentForms.size()).build();

    }*/


    /*
     * 新建学生
     * */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public Response createStudent(@RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school, @RequestBody JSONObject jsonParam) {
        Student student = JSONObject.parseObject(jsonParam.toJSONString(), Student.class);
        if (studentService.insertSelective(student) == 1)
            return Response.builder().status(STATUS.SUCCESS).message("新增学生成功，考号是" + student.getExam_id()).build();
        return Response.builder().status(STATUS.BAD_REQUEST).build();
    }

    /*
     * 获取单个学生信息
     * 根究考号
     * */
    @RequestMapping(value = "/{exam_id}", method = {RequestMethod.GET})
    public Response getStudentDetail(@PathVariable("exam_id") String exam_id) {
        List<StuCourse> stuCourses = stuCourseService.getById(exam_id);
        return Response.builder().status(STATUS.SUCCESS).data(stuCourses).build();
    }


    /*
     * 删除学生
     * */
    @RequestMapping(value = "/{exam_id}", method = {RequestMethod.DELETE})
    public Response deleteStudent(@PathVariable("exam_id") String exam_id) {
        if (studentService.delete(exam_id) == 1)
            return Response.builder().status(STATUS.SUCCESS).build();
        return Response.builder().status(STATUS.BAD_REQUEST).build();
    }


    /*
     * 更新学生信息
     * */
    @RequestMapping(value = "", method = {RequestMethod.PUT})
    public Response updateStudent(@RequestBody JSONObject jsonParam) {
        Student student = JSONObject.parseObject(jsonParam.toJSONString(), Student.class);
//        System.out.println(jsonParam.toJSONString());
        if (studentService.update(student) == 1)
            return Response.builder().status(STATUS.SUCCESS).build();
        return Response.builder().status(STATUS.BAD_REQUEST).build();

    }

    /*
    * 选课api
    * 没有用到
    * */
/*
    @RequestMapping(value = "/{exam_id}/courses/{course_id}", method = {RequestMethod.POST})
    public HashMap<String, Object> setStudentCourse(@PathVariable("exam_id") String exam_id, @PathVariable("course_id") String course_id, @RequestBody JSONObject jsonParam) {
        HashMap<String, Object> res = new HashMap<>();
        StuCourse stucourse = JSONObject.parseObject(jsonParam.toJSONString(), StuCourse.class);
        Student stu = studentService.getById(exam_id);
        courseSaleService.updateSaleByParams(course_id, stu.getMain_school(), stu.getSub_school());
        Course course = courseService.getById(course_id);
        stucourse.setWatch_time(0);
        stucourse.setReal_name(stu.getReal_name());
        stucourse.setCourse_name(course.getCourse_name());
        stucourse.setCatalogtree(course.getCatalogtree());
        */
/*
         * 改成norm_sum 按照课程数来
         * by zerkviii
         *  stucourse.setTotal_time(course.getNorm_duration());
         * *//*

        stucourse.setTotal_time(course.getNorm_sum());
        stucourse.setCourse_hours(course.getNorm_duration());

        */
/*
         * end zerkvii 2020-3.2
         * *//*

        int returncode = 0;
        returncode = stuCourseService.insertSelective(stucourse);
        if (returncode != 1) {
            res.put("code", 400);
            return res;
        }
        List<Examination> exams = examMapper.selectByCourseid(course_id);
        for (int i = 0; i < exams.size(); i++) {
            StuExam stuexam = new StuExam();
            stuexam.setCourse_id(course_id);
            stuexam.setExam_content(exams.get(i).getExam_content());
            stuexam.setExam_id(exam_id);
            stuexam.setExam_title(exams.get(i).getExam_title());
            stuexam.setExam_type(exams.get(i).getExam_type());
            stuexamMapper.insertSelective(stuexam);
        }
        res.put("code", 20000);
        res.put("data", "选课成功");
        return res;
    }


    @RequestMapping(value = "/getStuByTag", method = {RequestMethod.GET})
    public HashMap<String, Object> getStuByTag(@RequestParam("tag") String tag, @RequestParam("limit") int limit, @RequestParam("page") int page, @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school) {
        Tag cur_tag = tagService.getActiveTag();
        if (cur_tag.getTag_name().equals(tag.trim()))
            return this.SearchBySchool(main_school, sub_school, limit, page);
        HashMap<String, Object> res = new HashMap<>();
        int newlimit = (page - 1) * limit;
        int pagesize = limit;
        if (main_school.equals(sub_school)) {
            List<Student> stus = studentService.getByMainTag(tag, main_school, newlimit, pagesize);
            List<BigStudentForm> bigstus = new ArrayList<>();
            for (Student s : stus) {
                BigStudentForm big = new BigStudentForm();
                List<StuCourse> ls = histStuCourseMapper.getByIds(s.getExam_id(), tag);
                big.setStu(s);
                big.setCourses(ls);
                bigstus.add(big);
            }
            res.put("code", 20000);
            res.put("data", bigstus);
            res.put("total", studentService.getByMainTagSum(tag, main_school));
            return res;
        } else {
            List<Student> stus = studentService.getByTag(tag, newlimit, pagesize, main_school, sub_school);
            List<BigStudentForm> bigstus = new ArrayList<>();
            for (Student s : stus) {
                BigStudentForm big = new BigStudentForm();
                List<StuCourse> ls = histStuCourseMapper.getByIds(s.getExam_id(), tag);
                big.setStu(s);
                big.setCourses(ls);
                bigstus.add(big);
            }
            res.put("code", 20000);
            res.put("data", bigstus);
            res.put("total", studentService.getTagNum(tag, main_school, sub_school));
            return res;
        }
    }

    @RequestMapping(value = "/password", method = {RequestMethod.GET})
    public HashMap<String, Object> getPassword(@RequestParam("searchType") int searchType, @RequestParam("main_school") String main_school, @RequestParam("sub_school") String sub_school, @RequestParam("searchText") String searchText) {
        HashMap<String, Object> res = new HashMap<>();
        Map map = new HashMap<String, Object>();
        if (searchType == 1) {
            map.put("exam_id", searchText);
        } else
            map.put("id_card", searchText);
        if (main_school.equals(sub_school))
            map.put("main_school", main_school);
        else {
            map.put("main_school", main_school);
            map.put("sub_school", sub_school);
        }
        String password = studentService.getPassword(map);
        res.put("code", 20000);
        res.put("data", password);
        return res;
    }

*/

}
